package com.carkeeper.order.listener;

import com.alibaba.fastjson.JSON;
import com.carkeeper.order.config.RabbitMQConfig;
import com.carkeeper.order.pojo.SerOrder;
import com.carkeeper.order.service.SerOrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 超时监听
 */
@Component
public class OverTimeOrderListener {

    @Autowired
    private SerOrderService serOrderService;

    @RabbitListener(queues = RabbitMQConfig.OVERTIME_ORDER_QUEUE)
    public void receiveMessage(Channel channel, Message message) {

        SerOrder serOrder = JSON.parseObject(message.getBody(), SerOrder.class);

        int i = 0;
        if (serOrder != null) {
            //更改数据库
            i = serOrderService.overTimeUpdate(serOrder);
        }

        if (i <= 0) {
            //返回失败消息
            try {
                /*
                    参1:该消息的index
                    参2:是否批量.true:将一次性拒绝所有小于deliveryTag的消息
                    参3:被拒绝的是否重新入队列，true:重新回到原有队列中，默认回到头部
                 */
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //返回成功消息
            try {
                /*
                    参1:该消息的index
                    参2:是否批量处理.true:将一次性ack所有小于deliveryTag的消息
                 */
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
